# coding:utf8

from appserver import db_store
from sqlalchemy import or_
from models.entity.model_base import ModelBase

"""
设备类型
"""


class DeviceType(ModelBase):
    __tablename__ = "device_types"
    __main__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'编号')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'分类名称')
    code = db_store.Column(db_store.String(36), nullable=False, unique=True, comment=u"分类编码")
    icon = db_store.Column(db_store.String(32), comment=u"图标")
    description = db_store.Column(db_store.String(255), nullable=False, comment=u"描述")

    def __repr__(self):
        return "<DeviceType %s>" % self.name

    def to_dict(self):
        from models.entity.device import Device
        rdic = {}
        rdic["id"] = self.id
        rdic["name"] = self.name
        rdic["code"] = self.code
        rdic["icon"] = self.icon
        rdic["description"] = self.description
        rdic["device_number"] = len(Device.get_devices_by_type_id(self.id))
        return rdic

    @staticmethod
    def get_device_type_by_id(id_num):
        return DeviceType.query.filter_by(id=id_num).first()

    @staticmethod
    def get_device_type_by_name(name):
        return DeviceType.query.filter_by(name=name).first()

    @staticmethod
    def get_device_type_by_code(code):
        return DeviceType.query.filter_by(code=code).first()

    @staticmethod
    def get_device_type_all():
        return DeviceType.query.all()

    @staticmethod
    def search(query_word):
        data = []
        buttons = DeviceType.query.filter(
            or_(DeviceType.code.like('%' + query_word + '%'), DeviceType.name.like('%' + query_word + '%'),
                DeviceType.description.like('%' + query_word + '%'))).all()
        for obj in buttons:
            data.append(obj.to_dict())
        return data
